package com.ktjy.t382.ch01.util.Interceptor;

import com.ktjy.t382.ch01.pojo.SysUser;
import com.ktjy.t382.ch01.service.SysUserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;

public class AuthInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(AuthInterceptor.class);

    //    @Autowired
    private SysUserService sysUserService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("进入自定义拦截器");
//        String servletPath = request.getServletPath();
//        logger.info("Received request for path: {}", servletPath);
//        HttpSession session = request.getSession();
//        Object sysUser = session.getAttribute(Constants.SESSION_USER);
//        if (sysUser == null) {
//            response.sendRedirect("/error.jsp");
//            return false;
//        } else {
//            return true;
//        }
        // 获取请求参数
        String account = request.getParameter("account");
        String password = request.getParameter("password");

        // 调用服务层方法根据账号获取用户信息
        SysUser user = sysUserService.getSysUserByAccountBiz(account);

        // 如果用户不存在
        if (user == null) {
            // 记录日志并提示用户不存在，重定向到错误页面
            logger.info(account + "用户不存在");
            response.sendRedirect("/springmvc_war_exploded/error.jsp?msg=userNoExists");
            return false;
        } else if (!user.getPassword().equals(password)) {
            // 密码不正确，记录日志并提示密码错误，重定向到错误页面
            logger.info(account + "密码错误");
            response.sendRedirect("/springmvc_war_exploded/error.jsp?msg=passwordError");
            return false;
        }

        // 登录成功，将用户信息存储到会话中
        HttpSession session = request.getSession();
        session.setAttribute("user", user);
        logger.info(account + "登录成功");

        return true;
    }
}
